<template>
  <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="150px" size="small">
    <el-form-item label="优惠卷名称" prop="couponName">
      <el-input v-model.trim="ruleForm.couponName" placeholder="请输入优惠卷名称"></el-input>
    </el-form-item>

    <el-form-item label="单人发放数量" prop="couponDistributionQuantitySinglePerson">
      <el-input v-model.trim="ruleForm.couponDistributionQuantitySinglePerson" placeholder="请输入单人发放数量"></el-input>
    </el-form-item>

    <el-form-item label="类型" prop="couponType">
      <el-select v-model="ruleForm.couponType" placeholder="请选择类型" class="block">
        <el-option v-for="(i, k) in discountCouponTypes" :key="k" :label="i.label" :value="i.value"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="基础金额" prop="couponBaseAmount">
      <el-input v-model.trim="ruleForm.couponBaseAmount" placeholder="请输入基础金额"></el-input>
    </el-form-item>
    <el-form-item
      label="减少金额"
      prop="couponReducedAmount"
      v-if="hasCouponReducedAmount"
      class="striking"
    >
      <el-input v-model.trim="ruleForm.couponReducedAmount" placeholder="请输入减少金额"></el-input>
    </el-form-item>
    <el-form-item label="折扣" prop="couponDiscount" v-if="hasCouponDiscount" class="striking">
      <el-input v-model.trim="ruleForm.couponDiscount" placeholder="请输入折扣"></el-input>
    </el-form-item>

    <el-form-item label="有效期类型" prop="couponValidityTermType">
      <el-select v-model="ruleForm.couponValidityTermType" placeholder="请选择有效期类型" class="block">
        <el-option
          v-for="(i, k) in discountCouponValidity"
          :key="k"
          :label="i.label"
          :value="i.value"
        ></el-option>
      </el-select>
    </el-form-item>

    <el-form-item
      label="有效期期限"
      prop="_couponValidityTermRange"
      v-if="validityDateIsRange"
      class="striking"
    >
      <el-date-picker
        size="small"
        v-model="ruleForm._couponValidityTermRange"
        type="daterange"
        range-separator="-"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="yyyy-MM-dd"
      ></el-date-picker>
    </el-form-item>

    <el-form-item label="有效期期限" prop="couponValidityTerm" v-if="validityDateIsDay" class="striking">
      <el-input v-model.trim="ruleForm.couponValidityTerm" placeholder="请输入有效期期限"></el-input>
    </el-form-item>

    <el-form-item label="适用范围" prop="couponApplicableScope">
      <el-select
        v-model="ruleForm.couponApplicableScope"
        placeholder="请选择适用范围"
        class="block"
        @change="handleAppScopeChange"
      >
        <el-option
          v-for="(i, k) in discountCouponCategory"
          :key="k"
          :label="i.label"
          :value="i.value"
        ></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="适用对象" prop="couponApplicableResourceType">
      <el-select
        v-model="ruleForm.couponApplicableResourceType"
        placeholder="请选择适用对象"
        class="block"
        @change="ruleForm._couponApplicableResource = []"
      >
        <el-option v-for="(i, k) in applyCategory" :key="k" :label="i.label" :value="i.value"></el-option>
      </el-select>
    </el-form-item>

    <el-form-item
      label="关联"
      prop="_couponApplicableResource"
      class="striking"
      v-if="
        ruleForm.couponApplicableResourceType &&
        ruleForm.couponApplicableResourceType !== 'FRESH' &&
        ruleForm.couponApplicableResourceType !== 'MAINTENANCE'"
    >
      <TagBox closable v-model="ruleForm._couponApplicableResource" :props="tagBoxProps">
        <div
          @click="openPickerTable"
          slot="footer"
          style="text-align: center;cursor: pointer;color: #1ab394;margin-left: -50px;"
        >打开列表</div>
      </TagBox>
    </el-form-item>

    <el-form-item label="发放方式" prop="_couponDistributionMethodList">
      <el-select
        v-model="ruleForm._couponDistributionMethodList"
        multiple
        placeholder="请选择发放方式"
        class="block"
      >
        <el-option
          v-for="(i, k) in discountCouponMethods"
          :key="k"
          :label="i.label"
          :value="i.value"
        ></el-option>
      </el-select>
    </el-form-item>

    <el-form-item
      label="生鲜购物满基础金额"
      prop="_couponDistributionMethodBaseAmount_Refresh"
      v-if="hasFreshBaseAmount"
      class="striking"
    >
      <el-input
        v-model.trim="ruleForm._couponDistributionMethodBaseAmount_Refresh"
        placeholder="请输入生鲜购物满基础金额"
      ></el-input>
    </el-form-item>

    <el-form-item
      label="维保购物满基础金额"
      prop="_couponDistributionMethodBaseAmount_Maintenance"
      v-if="hasMaintenanceBaseAmount"
      class="striking"
    >
      <el-input
        v-model.trim="ruleForm._couponDistributionMethodBaseAmount_Maintenance"
        placeholder="请输入维保购物满基础金额"
      ></el-input>
    </el-form-item>

    <el-form-item label="简介" prop="couponSummary">
      <el-input v-model.trim="ruleForm.couponSummary" type="textarea" :rows="4"></el-input>
    </el-form-item>

    <el-form-item label="说明" prop="couponExplain">
      <t-editor v-model.trim="ruleForm.couponExplain" validateEvent></t-editor>
    </el-form-item>

    <Modal
      :onOk="handlePick"
      :onCancel="() => pickerModalVisible = false"
      :visible.sync="pickerModalVisible"
      :loading="pickerModalLoading"
      :width="$V.size.lg"
      appenmodelBody
      okText="选择"
      cancelText="关闭"
      title="关联"
    >
      <Picker
        ref="tmp"
        crossPick
        :type="pickerType"
        :lastPicked="ruleForm._couponApplicableResource"
      />
    </Modal>
    <el-form-item>
      <el-button type="primary" @click="handleSubmit">{{actionText}}</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
/* Mixins
------------------------------- */
import { Form, Emitter } from '@/mixins'

/* Components
------------------------------- */
import TagBox from '@/components/tag-box/TagBox'
import Picker from './CategoryPicker'
import TEditor from '@/components/editor/Editor'

/* Model
------------------------------- */
import {
  discountCouponModel,
  discountCouponCategory,
  discountCouponValidity,
  discountCouponMethods,
  discountCouponTypes,
  primaryKey
} from '../model'

import rule from '@/utils/rule'

export default {
  commentName: 'DiscountCouponForm',
  mixins: [Form('ruleForm', discountCouponModel), Emitter],
  components: { TagBox, Picker, TEditor },
  data () {
    return {
      discountCouponCategory,
      discountCouponTypes,
      discountCouponMethods,
      discountCouponValidity,
      ruleForm: this.initDefaults({
        couponDistributionQuantitySinglePerson: 1
      }),
      rules: {
        couponName: [
          {
            required: true,
            message: this.$t('required', { field: '优惠卷名称' })
          }
        ],
        couponSummary: [
          {
            required: true,
            message: this.$t('required', { field: '优惠卷简介' })
          }
        ],
        couponApplicableResourceType: [
          {
            required: true,
            trigger: 'change',
            message: this.$t('required', { field: '适用对象' })
          }
        ],

        couponBaseAmount: [
          {
            required: true,
            message: this.$t('required', { field: '基础金额' })
          },
          {
            pattern: rule.positiveDecimalRegex,
            message: this.$t('only accept postive decima')
          }
        ],

        couponReducedAmount: [
          {
            required: true,
            message: this.$t('required', { field: '减少金额' })
          },
          {
            pattern: rule.positiveDecimalRegex,
            message: this.$t('only accept postive decima')
          }
        ],

        _couponDistributionMethodBaseAmount_Maintenance: [
          {
            required: true,
            message: this.$t('required', { field: '维保购物满基础金额' })
          },
          {
            pattern: rule.positiveDecimalRegex,
            message: this.$t('only accept postive decima')
          }
        ],

        _couponDistributionMethodBaseAmount_Refresh: [
          {
            required: true,
            message: this.$t('required', { field: '生鲜购物满基础金额' })
          },
          {
            pattern: rule.positiveDecimalRegex,
            message: this.$t('only accept postive decima')
          }
        ],

        couponDiscount: [
          {
            required: true,
            message: this.$t('required', { field: '折扣' })
          }
        ],

        couponExplain: [
          {
            required: true,
            message: this.$t('required', { field: '说明' })
          }
        ],

        couponValidityTerm: [
          {
            required: true,
            message: this.$t('required', { field: '有效期期限' })
          },
          {
            pattern: rule.positiveIntegerRegex,
            message: this.$t('only accept postive integer')
          }
        ],

        couponDistributionQuantitySinglePerson: [
          {
            pattern: rule.positiveIntegerRegex,
            message: this.$t('only accept postive integer')
          }
        ],

        _couponValidityTermRange: [
          {
            required: true,
            type: 'array',
            trigger: 'change',
            message: this.$t('required', { field: '有效期期限' })
          }
        ],
        couponApplicableScope: [
          {
            required: true,
            trigger: 'change',
            message: this.$t('required', { field: '适用范围' })
          }
        ],

        couponType: [
          {
            required: true,
            trigger: 'change',
            message: this.$t('required', { field: '类型' })
          }
        ],

        couponValidityTermType: [
          {
            required: true,
            trigger: 'change',
            message: this.$t('required', { field: '有效期类型' })
          }
        ],

        _couponDistributionMethodList: [
          {
            required: true,
            trigger: 'change',
            type: 'array',
            message: this.$t('required', { field: '发放方式' })
          }
        ]
      },
      // -------- Picker ----------
      pickerModalVisible: false,
      pickerModalLoading: false,
      pickerType: ''
      // -------- !Picker ----------
    }
  },
  computed: {
    // 配置pickbox属性
    tagBoxProps () {
      return /classify/i.test(this.ruleForm.couponApplicableResourceType)
        ? {
          value: 'classifyId',
          label: 'classifyName'
        }
        : {
          value: 'goodsId',
          label: 'goodsName'
        }
    },
    // 选择分类或商品的主键
    pickPrimaryKey () {
      return this.tagBoxProps['value']
    },
    actionType () {
      return this.ruleForm[primaryKey] ? 'update' : 'create'
    },
    actionText () {
      return this.actionType === 'create'
        ? this.$t('createText')
        : this.$t('updateText')
    },
    applyCategory () {
      return this.ruleForm.couponApplicableScope === 'FRESH'
        ? [
          { value: 'FRESH', label: '所有商品' },
          { value: 'FRESH_GOODS', label: '生鲜商品' },
          { value: 'FRESH_CLASSIFY', label: '生鲜分类' }
        ]
        : this.ruleForm.couponApplicableScope === 'MAINTENANCE'
          ? [
            { value: 'MAINTENANCE', label: '所有商品' },
            { value: 'MAINTENANCE_GOODS', label: '维保商品' },
            { value: 'MAINTENANCE_CLASSIFY', label: '维保分类' }
          ]
          : []
    },
    validityDateIsRange () {
      return (
        this.ruleForm.couponValidityTermType === discountCouponValidity[0].value
      )
    },
    validityDateIsDay () {
      return (
        this.ruleForm.couponValidityTermType === discountCouponValidity[1].value
      )
    },

    hasCouponReducedAmount () {
      return this.ruleForm.couponType === discountCouponTypes[0].value
    },
    hasCouponDiscount () {
      return this.ruleForm.couponType === discountCouponTypes[1].value
    },
    hasCouponScope () {
      return !!this.ruleForm.couponApplicableScope
    },
    hasFreshBaseAmount () {
      return ~this.ruleForm._couponDistributionMethodList.indexOf(
        'FRESH_FULL_SHOPPING'
      )
    },
    hasMaintenanceBaseAmount () {
      return ~this.ruleForm._couponDistributionMethodList.indexOf(
        'MAINTENANCE_FULL_SHOPPING'
      )
    }
  },
  methods: {
    handleAppScopeChange (val) {
      this.ruleForm.couponApplicableResourceType = val
    },
    beforeSubmit (data) {
      // 处理两种购物满
      data.couponDistributionMethodList = data._couponDistributionMethodList.map(
        (code) => {
          let target = this.discountCouponMethods.find((k) => k.value === code)
          let couponDistributionMethodBaseAmount = ''

          if (code === discountCouponMethods[2].value) {
            couponDistributionMethodBaseAmount = this.ruleForm
              ._couponDistributionMethodBaseAmount_Refresh
          }
          if (code === discountCouponMethods[3].value) {
            couponDistributionMethodBaseAmount = this.ruleForm
              ._couponDistributionMethodBaseAmount_Maintenance
          }
          return {
            couponDistributionMethod: code,
            couponDistributionMethodValue: (target && target.label) || '',
            couponDistributionMethodBaseAmount
          }
        }
      )

      return data
    },
    handleSubmit () {
      try {
        this.submit((valid, values) => {
          if (valid) {
            this.$emit('submit', values)
          }
        })
      } catch (err) {
        this.$message.error(err.message)
      }
    },
    // ------------------------------ picker 开始 ------------------------------
    getSelection () {
      let selected = this.$refs.tmp.getSelection()

      return selected
    },

    handlePick () {
      try {
        this.$refs.tmp.assertSelection()

        const selects = this.getSelection()
        this.ruleForm._couponApplicableResource = selects
        this.pickerModalVisible = false
      } catch (err) {
        this.$message.warning(err.message)
      }
    },
    openPickerTable () {
      this.pickerType = this.ruleForm.couponApplicableResourceType
      this.pickerModalVisible = true
    }
    // ------------------------------ picker 结束 ------------------------------
  },
  mounted () {
    this.watchSelect('couponType', 'couponTypeValue', discountCouponTypes)

    this.watchSelect(
      'couponValidityTermType',
      'couponValidityTermTypeValue',
      discountCouponValidity
    )

    this.watchSelect(
      'couponApplicableScope',
      'couponApplicableScopeValue',
      discountCouponCategory
    )

    this.$watch(
      'ruleForm._couponValidityTermRange',
      (val) => {
        if (val && val.length) {
          this.ruleForm.couponValidityTermStart = val[0] || ''
          this.ruleForm.couponValidityTermEnd = val[1] || ''
        }
      },
      {
        immediate: true
      }
    )

    this.$watch(
      'ruleForm._couponApplicableResource',
      (val) => {
        if (val && val.length) {
          this.ruleForm.couponApplicableResource = val
            .map((it) => it[this.pickPrimaryKey])
            .join(',')
        }
      },
      {
        immediate: true
      }
    )
  }
}
</script>
<style lang="scss" scoped>
.striking {
  // 颜色加重提醒用户
  >>> .el-form-item__label {
    color: #1b8038;
    font-weight: bold;
    font-size: 12px;
  }
}
</style>
